﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Text.RegularExpressions;

namespace ComicViewer.IManhua
{
    public class IManhuaProxy
    {
        public List<ComicCategory> GetCategories()
        {
            List<ComicCategory> ccList = new List<ComicCategory>();
            for (int i = 0; i < 24; i++)
            {
                ComicCategory cc = new ComicCategory();
                cc.Name = new string((char)('A' + i), 1);
                ccList.Add(cc);
            }
            return ccList;
        }

        public List<ComicBook> GetBooks(ComicCategory category)
        {
            WebClient client = new WebClient();
            string content = client.DownloadString("http://www.imanhua.com/comic/"+category.Name+"/");

            int pageCount = 0;
            Regex regexPc = new Regex("共<strong>(?<pageCount>\\d*)</strong>页");
            MatchCollection matchPc = regexPc.Matches(content);
            if (matchPc.Count > 0)
            {
                pageCount = Convert.ToInt32(matchPc[0].Groups["pageCount"].Value);
            }

            //<a href="/comic/1873/"><img src="http://i2.imanhua.com/Cover/2010-07/Ajundezhanzhen.jpg" alt="A君的战争" /></a>
            Regex regex = new Regex("<a href=\"/comic/(?<bookID>\\d*)/\"><img src=\"(?<bookPic>[^<>]*)\" alt=\"(?<bookName>[^<>]*)\"");

            MatchCollection matchs = regex.Matches(content);
            for (int i = 0; i < matchs.Count; i++)
            {
                string bookID = matchs[i].Groups["bookID"].Value;
                string bookName = matchs[i].Groups["bookName"].Value;
                string bookPic = matchs[i].Groups["bookPic"].Value;

                ComicBook book = new ComicBook();
                book.ID = bookID;
                book.Name = bookName;
                book.PreviewUri = new Uri(bookPic, UriKind.Absolute);

                category.Books.Add(book);
            }

            for (int i = 1; i < pageCount; i++)
            {
                GetBooks(category, i);
            }
            return category.Books;
        }

        private void GetBooks(ComicCategory category, int pageIndex)
        {
            WebClient client = new WebClient();
            string content = client.DownloadString("http://www.imanhua.com/comic/" + category.Name + "/index_p"+(pageIndex+1).ToString()+".html");

            //<a href="/comic/1873/"><img src="http://i2.imanhua.com/Cover/2010-07/Ajundezhanzhen.jpg" alt="A君的战争" /></a>
            Regex regex = new Regex("<a href=\"/comic/(?<bookID>\\d*)/\"><img src=\"(?<bookPic>[^<>]*)\" alt=\"(?<bookName>[^<>]*)\"");

            MatchCollection matchs = regex.Matches(content);
            for (int i = 0; i < matchs.Count; i++)
            {
                string bookID = matchs[i].Groups["bookID"].Value;
                string bookName = matchs[i].Groups["bookName"].Value;
                string bookPic = matchs[i].Groups["bookPic"].Value;

                ComicBook book = new ComicBook();
                book.ID = bookID;
                book.Name = bookName;
                book.PreviewUri = new Uri(bookPic, UriKind.Absolute);

                category.Books.Add(book);
            }
        }
        private void GetBooks(List<ComicBook> books, string keyword, int pageIndex)
        {
            string encodeKeyword = System.Web.HttpUtility.UrlEncode(keyword, Encoding.GetEncoding("gb2312"));
            WebClient client = new WebClient();
            string content = client.DownloadString("http://www.imanhua.com/v2/user/search.aspx?key=" + encodeKeyword + "&p=" + (pageIndex + 1).ToString());
            //<a href="/comic/1873/"><img src="http://i2.imanhua.com/Cover/2010-07/Ajundezhanzhen.jpg" alt="A君的战争" /></a>
            Regex regex = new Regex("<a href=\"/comic/(?<bookID>\\d*)/\"><img src=\"(?<bookPic>[^<>]*)\" alt=\"(?<bookName>[^<>]*)\"");

            MatchCollection matchs = regex.Matches(content);
            for (int i = 0; i < matchs.Count; i++)
            {
                string bookID = matchs[i].Groups["bookID"].Value;
                string bookName = matchs[i].Groups["bookName"].Value;
                string bookPic = matchs[i].Groups["bookPic"].Value;

                ComicBook book = new ComicBook();
                book.ID = bookID;
                book.Name = bookName;
                book.PreviewUri = new Uri(bookPic, UriKind.Absolute);

                books.Add(book);
            }
        }

        public List<ComicTable> GetBookTable(ComicBook book)
        {
            WebClient client = new WebClient();
            string content = client.DownloadString("http://www.imanhua.com/comic/" + book.ID + "/");
            //<a href="/comic/205/list_32429.html" title="家庭教师 240话" target="_blank">家庭教师 240话</a>
            Regex regex = new Regex("href=\"/comic/" + book.ID + "/list_(?<tableID>\\d*).html\"[^>]*>(?<tableName>[^<>]*)<");

            MatchCollection matchs = regex.Matches(content);
            for (int i = 0; i < matchs.Count; i++)
            {
                string tableID = matchs[i].Groups["tableID"].Value;
                string tableName = matchs[i].Groups["tableName"].Value;
                ComicTable table = new ComicTable();
                table.Id = tableID;
                table.Name = tableName;
                book.AddTable(table);
            }
            return book.Tables;
        }

        public List<ComicPage> GetPages(ComicTable table)
        {
            //arrHost[0] = ['电信①', 'http://t4.mangafiles.com']; //t6
            //arrHost[1] = ['电信②', 'http://t5.mangafiles.com']; //t4
            //arrHost[2] = ['电信③', 'http://t6.mangafiles.com']; //t5
            //arrHost[3] = ['广东电信', 'http://t6.mangafiles.com']; //t6
            //arrHost[4] = ['江苏电信', 'http://t5.mangafiles.com']; //t4
            //arrHost[5] = ['网通', 'http://c5.mangafiles.com'];

            WebClient client = new WebClient();
            int pageCount = 0;
            string content = client.DownloadString("http://www.imanhua.com/comic/" + table.Book.ID + "/list_" + table.Id + ".html");
            //<option value="51">第51页</option></select>
            // 获取总页数
            Regex regex = new Regex("<option value=\"(?<pageCount>\\d*)\">[^<>]*</option></select>");

            MatchCollection matchs = regex.Matches(content);
            if (matchs.Count > 0)
            {
                pageCount = Convert.ToInt32(matchs[0].Groups["pageCount"].Value);
            }

            List<string> pageNumbers = new List<string>();

            if (pageNumbers.Count == 0)
            {
                Regex pageRegex4 = new Regex("[|\"]?(?<pageNumber>imanhua_[\\d]+_[\\d]+)[|\"]?");
                MatchCollection matchsPage4 = pageRegex4.Matches(content);
                foreach (Match match in matchsPage4)
                {
                    pageNumbers.Add(match.Groups["pageNumber"].Value);
                }
            }

            if (pageNumbers.Count == 0)
            {
                Regex pageRegex = new Regex("[|\"]?(?<pageNumber>imanhua_[\\d]+)[|\"]?");
                MatchCollection matchsPage = pageRegex.Matches(content);
                foreach (Match match in matchsPage)
                {
                    pageNumbers.Add(match.Groups["pageNumber"].Value);
                }
            }

            if (pageNumbers.Count == 0)
            {
                Regex pageRegex2 = new Regex("[|\"]?(?<pageNumber>JOJO_[\\d]+)[|\"]?");
                MatchCollection matchsPage2 = pageRegex2.Matches(content);
                foreach (Match match in matchsPage2)
                {
                    pageNumbers.Add(match.Groups["pageNumber"].Value);
                }
            }
            if (pageNumbers.Count == 0)
            {
                Regex pageRegex3 = new Regex("[|\"]?(?<pageNumber>[\\d]+)\\.[jpgpng]+[|\"]?");
                MatchCollection matchsPage3 = pageRegex3.Matches(content);
                foreach (Match match in matchsPage3)
                {
                    pageNumbers.Add(match.Groups["pageNumber"].Value);
                }
            }

            pageNumbers.Sort(new Comparison<string>((x,y)=>{

                if (x.Length > y.Length)
                {
                    return 1;
                }
                else if (x.Length < y.Length)
                {
                    return -1;
                }

                char[] cx = x.ToCharArray();
                char[] cy = y.ToCharArray();
                for (int i = 0; i < cx.Length; i++)
                {
                    if (cx[i] > cy[i])
                    {
                        return 1;
                    }
                    else if (cx[i] < cy[i])
                    {
                        return -1;
                    }
                }
                return 0;
            }));

            for (int i = 0; i < pageNumbers.Count; i++)
            {
                ComicPage page = new ComicPage();
                page.Index = i;
                page.Id = pageNumbers[i];
                page.PicUri = new Uri(
                    string.Format("{0}/Files/Images/{1}/{2}/{3}.jpg",
                    "http://t5.mangafiles.com",
                    table.Book.ID,
                    table.Id,
                    page.Id), UriKind.Absolute);
                page.PicUriPng = new Uri(
                    string.Format("{0}/Files/Images/{1}/{2}/{3}.png",
                    "http://t5.mangafiles.com",
                    table.Book.ID,
                    table.Id,
                    page.Id), UriKind.Absolute);

                page.ReferUrl = "http://www.imanhua.com/comic/" + table.Book.ID + "/list_" + table.Id + ".html";
                table.AddPage(page);
            }

            return table.Pages;
        }

        public List<ComicBook> SearchBooks(string keyword)
        {
            List<ComicBook> books = new List<ComicBook>();

            string encodeKeyword = System.Web.HttpUtility.UrlEncode(keyword, Encoding.GetEncoding("gb2312"));
            WebClient client = new WebClient();
            string content = client.DownloadString("http://www.imanhua.com/v2/user/search.aspx?key=" + encodeKeyword);

            int pageCount = 0;
            Regex regexPc = new Regex("共<strong>(?<pageCount>\\d*)</strong>页");
            MatchCollection matchPc = regexPc.Matches(content);
            if (matchPc.Count > 0)
            {
                pageCount = Convert.ToInt32(matchPc[0].Groups["pageCount"].Value);
            }

            //<a href="/comic/1873/"><img src="http://i2.imanhua.com/Cover/2010-07/Ajundezhanzhen.jpg" alt="A君的战争" /></a>
            Regex regex = new Regex("<a href=\"/comic/(?<bookID>\\d*)/\"><img src=\"(?<bookPic>[^<>]*)\" alt=\"(?<bookName>[^<>]*)\"");

            MatchCollection matchs = regex.Matches(content);
            for (int i = 0; i < matchs.Count; i++)
            {
                string bookID = matchs[i].Groups["bookID"].Value;
                string bookName = matchs[i].Groups["bookName"].Value;
                string bookPic = matchs[i].Groups["bookPic"].Value;

                ComicBook book = new ComicBook();
                book.ID = bookID;
                book.Name = bookName;
                book.PreviewUri = new Uri(bookPic, UriKind.Absolute);

                books.Add(book);
            }

            for (int i = 1; i < pageCount; i++)
            {
                GetBooks(books, keyword, i);
            }

            return books;
        } 
    }
}
